package service;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

import core.NewOption;
import core.NewOptions;

public class OptionsConverter implements Converter {

	public boolean canConvert(Class type) {
		return type.equals(NewOptions.class);
	}

	public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
		writer.flush();
		NewOptions options = (NewOptions) source;
		for (NewOption option : options.getOptions()) {
			writer.startNode("option");
			writer.addAttribute("name", option.getLabel());
			if (option.getType().equals(Boolean.TYPE)) {
				String value = (Boolean) option.getValue() ? "Y" : "N";
				writer.addAttribute("value", value);
			}
			if (option.getType().equals(Integer.TYPE)) {
				Integer value = Integer.valueOf("" + option.getValue());
				writer.addAttribute("value", value.toString());
			}
			writer.endNode();
		}
	}

	public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
		NewOptions result = new NewOptions(false);
		if (reader.getNodeName().equals("options")) {
			while (reader.hasMoreChildren()) {
				reader.moveDown();
				NewOption option = NewOption.getOption(reader.getAttribute("name"));
				String value = reader.getAttribute("value");
				if (option.getType().equals(Boolean.TYPE)) {
					option.setValue(value.equals("Y"));
				}
				if (option.getType().equals(Integer.TYPE)) {
					option.setValue(value);
				}
				result.addOption(option);
				reader.moveUp();
			}
		}
		return result;
	}

}
